package cn.morge.springbootquartz.service.impl;

import cn.morge.springbootquartz.entity.GoodInfoEntity;
import cn.morge.springbootquartz.repository.GoodInfoRepository;
import cn.morge.springbootquartz.service.GoodInfoService;
import cn.morge.springbootquartz.timetask.GoodAddTimer;
import cn.morge.springbootquartz.timetask.GoodStockCheckTimer;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.UUID;

/**
 * @author 麻贵海
 * 创建时间:2018/08/05 21:16
 * 项目名称:esim
 * @version 1.0
 * @since JDK 1.8
 * 类说明:
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class GoodInfoServiceImpl implements GoodInfoService {

    /**
     * 注入任务调度器
     */
    @Autowired
    private Scheduler scheduler;

    /**
     * 商品数据接口
     */
    @Autowired
    private GoodInfoRepository goodInfoRepository;

    @Override
    public Long save(GoodInfoEntity good) throws Exception {
        goodInfoRepository.save(good);

        // 构建创建商品定时任务
        buildCreateGoodTimer();
        // 构建商品库存定时任务
        buildGoodStockTimer();

        return good.getId();
    }

    /**
     * 构建创建商品定时任务
     *
     * @throws Exception
     */
    public void buildCreateGoodTimer() throws Exception {
        // 定义时间开始为1分钟后
        long startTime = System.currentTimeMillis() + 10000 * 60;
        // 任务名称
        String taskName = UUID.randomUUID().toString();
        // 任务所属分组
        String taskGroup = GoodAddTimer.class.getName();
        // 创建任务
        JobDetail jobDetail = JobBuilder.newJob(GoodAddTimer.class).withIdentity(taskName, taskGroup).build();
        // 创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).startAt(new Date(startTime)).build();
        // 将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 商品库存检查调度器
     *
     * @throws Exception
     */
    public void buildGoodStockTimer() throws Exception {
        // 任务名称
        String taskName = UUID.randomUUID().toString();
        // 任务所属分组
        String taskGroup = GoodStockCheckTimer.class.getName();
        // cron表达式，30秒钟执行一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/30 * * * * ?");
        // 创建任务
        JobDetail jobDetail = JobBuilder.newJob(GoodStockCheckTimer.class).withIdentity(taskName, taskGroup).build();
        // 创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).withSchedule(cronScheduleBuilder).build();

        // 将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
